import java.util.ArrayList;
import java.util.List;

/**
 * 39. 组合总和
 */
public class Solution_39 {
    /**
     * 官方题解：搜索回溯（不太懂）
     * 
     * @param candidates
     * @param target
     * @return
     */
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> combine = new ArrayList<>();
        dfs(candidates, target, ans, combine, 0);
        return ans;
    }

    /**
     * 当前在 candidates 数组的第 index 位，还剩 target 要组合，已经组合的列表为 combine
     * 
     * @param candidates
     * @param target
     * @param ans
     * @param combine
     * @param index
     */
    private void dfs(int[] candidates, int target, List<List<Integer>> ans, List<Integer> combine, int index) {
        if (index == candidates.length) {
            return;
        }
        if (target == 0) {
            ans.add(new ArrayList<Integer>(combine));
            return;
        }
        // 直接跳过
        dfs(candidates, target, ans, combine, index + 1);
        // 选择当前数
        if (target - candidates[index] >= 0) {
            combine.add(candidates[index]);
            dfs(candidates, target - candidates[index], ans, combine, index);
            combine.remove(combine.size() - 1);
        }
    }

    public static void main(String[] args) {
        Solution_39 solution = new Solution_39();
        int[] candidates = { 2, 3, 5 };
        int target = 8;
        List<List<Integer>> ans = solution.combinationSum(candidates, target);
        System.out.println(ans);
    }
}
